package net.jcip.examples.chapter6.thread.ThreadPool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * 线程池执行任务时调用 shutdown()，然后再尝试提交新任务会被拒绝 的场景
 *
 */
public class ThreadPoolShutdownDemo {

    // 自定义线程工厂，便于观察线程执行情况
    static class NamedThreadFactory implements ThreadFactory {
        private final AtomicInteger counter = new AtomicInteger(1);
        private final String prefix;

        public NamedThreadFactory(String prefix) {
            this.prefix = prefix;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(prefix + "-" + counter.getAndIncrement());
            t.setDaemon(false);
            return t;
        }
    }

    public static void main(String[] args) {
        // 创建一个固定线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, 4,
                30, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(5),
                new NamedThreadFactory("demo-worker"),
                new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
        );

        // 提交一些任务
        for (int i = 1; i <= 5; i++) {
            int taskId = i;
            executor.submit(() -> {
                System.out.println(Thread.currentThread().getName() + " 执行任务 " + taskId);
                try {
                    Thread.sleep(3000); // 模拟任务执行耗时
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " 被中断！");
                    Thread.currentThread().interrupt();
                }
            });
        }

        System.out.println("=== 已提交初始任务 ===");

        // 调用 shutdown()，开始拒绝新任务
        System.out.println("调用 shutdown()，线程池开始拒绝新任务...");
        executor.shutdown();

        // 再尝试提交新任务
        try {
            executor.submit(() -> System.out.println("新任务执行"));
        } catch (RejectedExecutionException e) {
            System.out.println("新任务被拒绝，线程池已关闭: " + e);
        }

        // 等待线程池任务完成
        try {
            if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                System.out.println("部分任务未完成，超时退出");
            }
        } catch (InterruptedException e) {
            System.out.println("等待线程池关闭被中断");
            Thread.currentThread().interrupt();
        }

        System.out.println("线程池关闭完成");
    }
}
